package com.qingcheng.service.impl;

import com.alibaba.druid.filter.AutoLoad;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.BrandMapper;
import com.qingcheng.service.goods.SkuSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuSearchServiceImpl implements SkuSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private BrandMapper brandMapper;
    private static final String SKU_INDEX_NAME = "sku";


    @Override
    public Map search(Map<String, String> searchMap) {
        SearchRequest searchRequest = new SearchRequest(SKU_INDEX_NAME);
        searchRequest.types("doc");  //设置查询的类型
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();//布尔查询构建器
        //1.1  关键字搜索
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", searchMap.get("keywords"));
        boolQueryBuilder.must(matchQueryBuilder);
        if (searchMap.get("category") != null) {
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("categoryname", searchMap.get("category"));
            boolQueryBuilder.filter(termQueryBuilder);
        }

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        TermsAggregationBuilder termsAggregationBuilder =
                AggregationBuilders.terms("sku_category").field("categoryname");
        searchSourceBuilder.aggregation(termsAggregationBuilder);

        TermsAggregationBuilder brandTermsAggregationBuilder =
                AggregationBuilders.terms("sku_brand").field("brandname");
        searchSourceBuilder.aggregation(brandTermsAggregationBuilder);

        searchRequest.source(searchSourceBuilder);

        Map resultMap = new HashMap();
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            long totalHits = searchHits.getTotalHits();
            System.out.println("记录数：" + totalHits);
            SearchHit[] hits = searchHits.getHits();
            //2.1  商品列表
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            for (SearchHit hit : hits) {
                Map<String, Object> skuMap = hit.getSourceAsMap();
                resultList.add(skuMap);
            }
            resultMap.put("rows", resultList);
            ArrayList<String> categoryList = new ArrayList<String>();
            Aggregations aggregations = searchResponse.getAggregations();
            Map<String, Aggregation> asMap = aggregations.getAsMap();
            Terms terms = (Terms) asMap.get("sku_category");
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                System.out.println(bucket.getKeyAsString() + ":" + bucket.getDocCount());
                categoryList.add(bucket.getKeyAsString());
            }
//                    ArrayList<String> brandList = new ArrayList<>();
//                    Aggregations brandAggregations = searchResponse.getAggregations();
//                    Map<String, Aggregation> bAsMap = brandAggregations.getAsMap();
//                    Terms brandTerms = (Terms) bAsMap.get("sku_brand");
//                    List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
//                    for(Terms.Bucket bucket:brandBuckets){
//                        brandList.add(bucket.getKeyAsString());
//                    }

            String categoryname = "";//商品分类名称
            if (searchMap.get("category") == null) {//如果没有分类条件
                if (categoryList.size() > 0) {
                    categoryname = categoryList.get(0);//提取分类列表的第一个分类
                }
            } else {
                categoryname = searchMap.get("category");//取出参数中的分类
            }
            List<Map> brandList = brandMapper.findListByCategoryName(categoryname);//查询品牌列表

            resultMap.put("categoryList", categoryList);
            resultMap.put("brandList", brandList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

}
